package com.mall.dubbo.api;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.mall.dubbo.mapper.UmsMenuMapper;
import com.mall.dubbo.mapper.UmsRoleMapper;
import com.mall.dubbo.mapper.UmsRoleMenuRelationMapper;
import com.mall.dubbo.mapper.UmsRoleResourceRelationMapper;
import com.mall.model.domain.UmsMenu;
import com.mall.model.domain.UmsRole;
import com.mall.model.domain.UmsRoleResourceRelation;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

/**
 * @author xyiaao
 * @description 针对表【ums_role(后台用户角色表)】的数据库操作Api实现
 * @createDate 2022-03-29 19:46:09
 */
@DubboService
public class UmsRoleApiImpl extends ServiceImpl<UmsRoleMapper, UmsRole>
        implements UmsRoleApi {

    @Autowired
    private UmsRoleMapper umsRoleMapper;

    @Autowired
    private UmsRoleMenuRelationMapper umsRoleMenuRelationMapper;

    @Autowired
    private UmsMenuMapper umsMenuMapper;

    @Autowired
    private UmsRoleResourceRelationMapper umsRoleResourceRelationMapper;


    @Override
    public UmsRole findUmsRoleByUmsAdminId(Long umsAdminId) {

        return umsRoleMapper.findUmsRoleByUmsAdminId(umsAdminId);
    }

    //根据角色名称分页获取角色列表
    public Page<UmsRole> findByName(String keyword, Integer pageNum, Integer pageSize) {

        Page<UmsRole> page = new Page<>(pageNum, pageSize);

        LambdaQueryWrapper<UmsRole> lqw = new LambdaQueryWrapper<>();
        lqw.like(keyword != null, UmsRole::getName, keyword);

        return umsRoleMapper.selectPage(page, lqw);
    }

    //添加角色
    public void createRole(UmsRole role) {

        umsRoleMapper.insert(role);
    }

    //删除角色
    public void delete(List<Long> ids) {

        umsRoleMapper.deleteBatchIds(ids);

    }

    //获取所有角色
    public List<UmsRole> listAll() {

        LambdaQueryWrapper<UmsRole> lqw = new LambdaQueryWrapper<>();
        lqw.eq(UmsRole::getStatus, 1);

        return umsRoleMapper.selectList(lqw);

    }

    //获取角色相关菜单
    public List<UmsMenu> listMenu(List<Long> menuIds) {

        LambdaQueryWrapper<UmsMenu> lqw = new LambdaQueryWrapper<>();
        lqw.in(CollUtil.isNotEmpty(menuIds), UmsMenu::getId, menuIds);

        return umsMenuMapper.selectList(lqw);
    }

    //修改角色
    public void updateRole(Integer id, UmsRole role) {

        LambdaQueryWrapper<UmsRole> lqw = new LambdaQueryWrapper<>();
        lqw.eq(id != null, UmsRole::getId, id);

        umsRoleMapper.update(role, lqw);

    }

    @Override
    public void deleteByRoleId(Integer roleId) {

        LambdaQueryWrapper<UmsRoleResourceRelation> lqw = new LambdaQueryWrapper<>();
        lqw.eq(roleId != null, UmsRoleResourceRelation::getRoleId, roleId);
        umsRoleResourceRelationMapper.delete(lqw);
    }

}




